﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using XfTechOAWeb.IService;
using XfTechOAWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using XfTechOAWeb.Dtos;
using Microsoft.AspNetCore.Hosting;

namespace XfTechOAWeb.Controllers
{
    /// <summary>
    /// 用户模块
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize]  //授权特性，表示：下面的控制器中所有方法，都必须登录之后才能访问
    public class UserController : ControllerBase
    {

        private readonly IUserService _userService;
        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 添加用户接口
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(UserAddDto user)
        {
            if (!ModelState.IsValid)
            {
                return  Ok(new ResponseModel<object>() { Code = 400, Msg = "数据未导入" });
            }
            int data = _userService.Add(user);
            if(data>0)
            {
                return Ok(new ResponseModel<object>() { Code = 200,Data=data, Msg = "添加成功!" });
            }
            else
            {
                return Ok(new ResponseModel<object>() { Code = 200, Data = data, Msg = "账号已经存在,请重新输入!" });
            }
            
        }

        /// <summary>
        /// 更新用户接口
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Put(UserUptDto user)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object>() { Code =500, Msg = "数据未导入" });

            }
            int data = _userService.Upt(user);
            if(data>0)
            {
                return Ok(new ResponseModel<object>() { Code = 200, Data =1, Msg = "修改成功!" });
            }
            else
            {
                return Ok(new ResponseModel<object>() { Code = 200, Data =0, Msg = "密码与原密码相同,请重新输入!" });
            }
            
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult Delete(string ids)
        {
            if (ids == "")
            {
                return Ok(new ResponseModel<object>() { Code = 400, Msg = "数据未导入" });

            }
            return Ok(new ResponseModel<object>() { Code = 200, Data = _userService.Del(ids), Msg = "删除成功!" });
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get([FromQuery] UserPageRequestDto input)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object>() { Code = 400, Msg = "数据未导入" });
            }
            //获取分页数据
            var page = _userService.GetList(input);
            return Ok(new ResponseModel<object>() { Code = 200, Data =new { total = page.TotalCount, list = page.PageList }, Msg = "查询成功!" });

        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("id")]
        public IActionResult Get(int id)
        {

            if (id == 0)
            {
                return Ok(new ResponseModel<object>() { Code = 400, Msg = "获取失败!" });
            }
            //获取分页数据
            var user = _userService.Get(id);
            return Ok(new ResponseModel<object>() { Code = 200, Data =user, Msg = "查找成功!" });
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        [HttpGet("userid")]
        public IActionResult UserGet()
        {
            var cl = HttpContext.User.FindFirst("UId").Value;
            var userId = int.Parse(cl);
            //获取分页数据
            var user = _userService.Get(userId);
            return Ok(new ResponseModel<object>() { Code = 200, Data = user, Msg = "查找成功!" });
        }

        /// <summary>
        /// 给用户添加角色
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="rid"></param>
        /// <returns></returns>
        [HttpPost("urole")]
        public IActionResult Post(UserRoleAddDto urole)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new ResponseModel<object>() { Code = 400, Msg = "数据未导入成功!" });
            }

            //执行添加
            int result = _userService.AddUserRole(urole);
            if(result>0)
                return Ok(new ResponseModel<object>() { Code = 20001, Data = result, Msg = "给用户添加角色成功" });
            else
                return Ok(new ResponseModel<object>() { Code = 20005, Data = result, Msg = "给用户添加角色失败" });

        }

        /// <summary>
        /// 用户修改密码
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPut("password")]
        public IActionResult Put(UserPassUpt password)
        {
            if (password == null)
            {
                return Ok(new ResponseModel<object>() { Code = 400, Msg = "数据未导入成功!" });
            }
            return Ok(new ResponseModel<object>() { Code = 200, Data = _userService.PasswordUpt(password), Msg = "修改成功!" });
        }

        /// <summary>
        /// 向webapi发送请求执行导入操作
        /// </summary>
        /// <param name="token">身份验证token</param>
        /// <param name="reauestUrl">api请求完整路径</param>
        /// <param name="bytes">文件byte[]</param>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        /// 
        //[HttpPost]
        ////[AllowAnonymous]
        //public string PostImport()
        //{
        //    HttpClient httpClient = new HttpClient();
        //    //httpClient.BaseAddress = new Uri(reauestUrl);
        //    //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", token);
        //    //httpClient.DefaultRequestHeaders.Add("Authorization", token);
        //    string requesturl = @"https://localhost:5001/api/Default/Upload";
        //    FileStream fs = new FileStream(@"XfTechOAWeb.ApiServer.xml", FileMode.Open, FileAccess.Read);
        //    byte[] bytes = new byte[fs.Length];
        //    fs.Read(bytes, 0, bytes.Length);
        //    fs.Close();

        //    string fileName = "XfTechOAWeb.ApiServer.xml";
        //    ByteArrayContent fileContent = new ByteArrayContent(bytes);

        //    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        //    {
        //        Name = "file",
        //        FileName = fileName
        //    };
        //    MultipartFormDataContent content = new MultipartFormDataContent();
        //    content.Add(fileContent);
        //    var result = httpClient.PostAsync(requesturl, content);

        //    return result.Result.Content.ReadAsStringAsync().Result;
        //}

        [HttpGet("GetExportExcel")]
        [AllowAnonymous]
        public IActionResult GetExportExcel(string key, [FromServices]IWebHostEnvironment environment)
        {
            string path = environment.WebRootPath + @"\Files\1.xlsx";


            return File(
                new FileStream(path, FileMode.Open),
                "application/octet-stream",
                "花名册.xlsx"
            );
        }
    }
}